<template>
  <div class="max-w-4xl mx-auto p-5">
    <ForumPostHeader
      title="发布新帖"
      subtitle="分享你的技术经验和学习心得"
      back-text="返回论坛"
      @back="goBack"
    />

    <form class="bg-white rounded-xl shadow-sm p-8" @submit.prevent="submitPost">
      <ForumPostEditor
        v-model="form"
        v-model:show-preview="showPreview"
        ref="postEditor"
      />

      <ForumPostActions
        :can-submit="canSubmit"
        :submitting="submitting"
        :show-preview="showPreview"
        submit-text="发布帖子"
        submitting-text="发布中..."
        @preview="togglePreview"
        @cancel="goBack"
        @submit="submitPost"
      />
    </form>
  </div>
</template>

<script setup lang="ts">
import type { CreatePostRequest } from '~/types/post'
import { postApi } from '~/utils/api'

// 添加认证中间件
definePageMeta({
  middleware: 'auth'
})

// 响应式数据
const form = ref<CreatePostRequest>({
  title: '',
  content: ''
})

const submitting = ref(false)
const showPreview = ref(false)
const postEditor = ref()

// 计算属性
const canSubmit = computed(() => {
  return form.value.title.trim().length > 0 && 
         form.value.content.trim().length > 0 &&
         !submitting.value
})

// 方法
const submitPost = async () => {
  if (!canSubmit.value) return
  
  try {
    submitting.value = true
    
    const response = await postApi.createPostApi({
      title: form.value.title.trim(),
      content: form.value.content.trim()
    })
    
    if (response.success) {
      console.log('帖子发布成功！')
      navigateTo(`/StudyArea/Forum/Post/${response.data.id}`)
    }
  } catch (error) {
    console.error('发布帖子失败:', error)
  } finally {
    submitting.value = false
  }
}

const goBack = () => {
  if (form.value.title || form.value.content) {
    // 简单的确认对话框
    if (confirm('您有未保存的内容，确定要离开吗？')) {
      navigateTo('/StudyArea/Forum')
    }
  } else {
    navigateTo('/StudyArea/Forum')
  }
}

const togglePreview = () => {
  showPreview.value = !showPreview.value
}
</script>

